package com.spirit.controler.user;

import com.spirit.dao.userdao.AderessDao;
import com.spirit.dao.userdao.UserDao;
import com.spirit.domain.user.Aderess;
import com.spirit.domain.user.User;
import com.spirit.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@SessionAttributes("sessionUser")
@Controller
@RequestMapping("/user")
public class UserControler {
    private final String SUCCESS = "user/userRegisterSuccess";

    @Autowired
    private UserService userService;
    @Autowired
    private AderessDao aderessDao;
    @Autowired
    private UserDao userDao;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    /**
     * 测试requestmapping
     *
     * @return
     */
    @RequestMapping(value = "/helloworld", params = {"userName=123", "userAge!=20"},
            headers = {"Accept-Language=zh-CN,zh;q=0.9,en;q=0.8"})
    //@RequestMapping(value = "/helloworld",params = {"userName = 123","userAge"})
    //@RequestMapping(value = "/helloworld",params = "123")
    public String helloWorld() {
        System.out.println("hello world!");
        return "success";
    }

    //测试输出JSON格式
    @ResponseBody
//    @RequestMapping(value = "/testPathVariable/{userid}", produces = "application/json;charset=UTF-8")
    @RequestMapping(value = "/testPathVariable/{userid}")
    public User testPathVariable(@PathVariable("userid") String userid) {
        User user = new User();
        user.setUserName(userid);
        return user;
    }

    /**
     * 跳转到注册页面
     * @return
     */
    @RequestMapping(value = "/regist")
    public String toRegist() {
        System.out.println("regist");
        return "user/regist";
    }

    /**
     * 创建用户
     * @param user
     * @return
     */
    //@RequestMapping(value = "/createUser", method = RequestMethod.POST)
    @RequestMapping(value = "/createUser")
    public ModelAndView createUser(User user) {
        System.out.println(user.getUserName());
        System.out.println(user.getPassWord());
        System.out.println(user.getConfirmPassWord());
        System.out.println(user.getAderess().getStreet());
        System.out.println(user.getAderess().getCity());
        System.out.println(user.getAderess().getProvince());
        userService.createUser(user);
        ModelAndView modelAndViewl = new ModelAndView();
        modelAndViewl.setViewName(SUCCESS);
        modelAndViewl.addObject("user", user);
        return modelAndViewl;
    }

    /**
     * 测试@RequestParam
     * @param userName
     * @param age
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(path = "/testRequestParam")
    public ModelAndView testRequestParam(
            @RequestParam("userName") String userName,
            @RequestParam(value = "userAge", required = false, defaultValue = "0") Integer age,
            HttpServletRequest request, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(SUCCESS);
        User user = new User();
        user.setUserName(userName);
        user.setUserAge(age);
        modelAndView.addObject("user", user);
        request.setAttribute("username", userName);
        session.setAttribute("username", userName);
        System.out.println("request.getAttribute(\"username\") = " + request.getAttribute("username"));
        System.out.println("session.getAttribute(\"username\") = " + session.getAttribute("username"));
        return modelAndView;
    }

    /**
     * 测试@RequestHeader
     * @param al
     * @param sessionId
     * @param userAgent
     * @return
     */
    @RequestMapping(path = "/testRequestHeader")
    public ModelAndView testRequestHeader(
            @RequestHeader("Accept-Language") String al,
            @CookieValue("JSESSIONID") String sessionId,
            @RequestHeader("User-Agent") String userAgent) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(SUCCESS);
        User user = new User();
        user.setHeader(al);
        user.setSessionId(sessionId);
        user.setUserAgent(userAgent);
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    /**
     * 测试@MatrixVariable
     * @param userId
     * @param param
     * @return
     */
    @RequestMapping(path = "/testMatrixVariable/{userId}", method = RequestMethod.GET)
    public ModelAndView testMatrixVariable(
            @PathVariable String userId,
            @MatrixVariable(required = false, defaultValue = "0") Integer param) {
        System.out.println("testMatrixVariable——userId：" + userId);
        System.out.println("testMatrixVariable——param：" + param);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(SUCCESS);
        User user = new User();
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    /**
     * 测试输出格式为map
     * @param id
     * @param userAge
     * @param map
     * @return
     */
    @RequestMapping(path = "/testSpringMVCMap")
    public String testSpringMVCMap(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id,
                                   @RequestParam(value = "userAge", required = false, defaultValue = "0") Integer userAge,
                                   Map<String, String> map) {
        map.put("userName", "admin");
        return SUCCESS;
    }

    /**
     * @ModelAttributes
     * @param id
     * @param map
     */
    @ModelAttribute
    public void getUser(@RequestParam(value = "id", required = false) Integer id,
                        Map<String, Object> map) {
        User user = new User();
        if (id != null) {
            user = userDao.getUser(id);
            System.out.println("from db User:" + user);
        }
        map.put("user", user);
    }

//    @ModelAttribute
//    public void getUser(User user,
//                        Map<String,Object> map){
//        User user1 = userDao.getUser(user.getId());
//        System.out.println("from db User:" + user1);
//        map.put("user",user1);
//    }

    /**
     * 测试@ModelAttribute
     * @param user
     * @return
     */
    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(@ModelAttribute("user") User user) {
        System.out.println(user);
        return SUCCESS;
    }

    /**
     * 测试sessionAttribute
     * @param map
     * @return
     */
    @RequestMapping("/testSessionAttributes")
    public String testSessionAttributes(Map<String, Object> map) {
        User user = new User("jack", "123456", 20, 123);
        map.put("sessionUser", user);
        System.out.println("session User:" + user);
        return SUCCESS;
    }

    /**
     * 测试internalviewresovler
     * @return
     */
    @RequestMapping("/testInternal")
    public String testInternal() {
        return "success";
    }

    /**
     * 测试重定向
     * @return
     */
    @RequestMapping("/testRedirect")
    public String testRedirect() {
        System.out.println("test redirect");
        return "redirect:/index.jsp";
    }

    /**
     * 测试自定义视图
     * @return
     */
    @RequestMapping("/testCustmView")
    public String testCustmView() {
        return "helloView";
    }

    /**
     * 查询用户列表
     * @param map
     * @return
     */
    @RequestMapping("/users")
    public String users(Map<String, Object> map) {
        map.put("users", userService.listUser());
        return "user/users";
    }

    /**
     * 跳转到新增页面
     * @param map
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String toAdduser(Map<String, Object> map) {
        System.out.println("跳转到新增页面");
        Map<String, String> genderMap = new HashMap();
        genderMap.put("1", "男");
        genderMap.put("2", "女");
        map.put("genders", genderMap);
        map.put("aderessList", aderessDao.listAderess());
        map.put("user", new User());
        return "user/user";
    }

    /**
     * 新增用户
     * @param user
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String addUser(@Valid User user, BindingResult result,Map<String,Object> map) {
        System.out.println("新增用户");
        System.out.println(user.toString());

        if(result.getErrorCount() > 0) {
            System.out.println("出错了！");
            for(FieldError fieldError:result.getFieldErrors()) {
                System.out.println("错误字段：" + fieldError.getField() + "，错误信息是：" +  fieldError.getDefaultMessage());
            }

            Map<String, String> genderMap = new HashMap();
            genderMap.put("1", "男");
            genderMap.put("2", "女");
            map.put("genders", genderMap);
            map.put("aderessList", aderessDao.listAderess());
            map.put("user", user);

            return "user/user";
        }
        Aderess aderess = aderessDao.getAderess(user.getAderess().getId());
        user.setAderess(aderess);
        userService.createUser(user);
        return "redirect:/user/users";
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("userId") Integer userId) {
        System.out.println("删除用户");
        userDao.removeUser(userId);
        return "redirect:/user/users";
    }

    /**
     * 跳转到修改页面
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public String toUpdateUser(@PathVariable("id") Integer id, Map<String, Object> map) {
        System.out.println("跳转到修改页面");
        Map<String, String> genderMap = new HashMap();
        genderMap.put("1", "男");
        genderMap.put("2", "女");
        map.put("genders", genderMap);
        map.put("aderessList", aderessDao.listAderess());
        map.put("user", userDao.getUser(id));
        return "user/user";
    }

    /**
     * REST风格的修改
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    public String updateUser(User user) {
        userDao.updateUser(user);
        return "redirect:/user/users";
    }

    /**
     * 测试converter
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/testUserConverter")
    public String testConverter(@RequestParam("user") User user) {
        userService.createUser(user);
        return "redirect:/user/users";
    }

    @ResponseBody
    @RequestMapping("/listAllUser")
    public Collection<User> listAllUser() {
        return userDao.listUsers();
    }
}
